# _*_ coding: utf-8 _*_
import	os
import	sys
import	string
import	re
import	urllib;
import	urllib2;

class YDdict: 
	def get_elements_by_path(self,xml, elem):
		if type(xml) == type(''):
			xml = [xml];
		if type(elem) == type(''):
			elem = elem.split('/');
		if (len(xml) == 0):
			return [];
		elif (len(elem) == 0):
			return xml;
		elif (len(elem) == 1):
			result = [];
			for item in xml:
				result += self.get_elements(item, elem[0]);
			return result;
		else:
			subitems = [];
			for item in xml:
				subitems += self.get_elements(item, elem[0]);
			return self.get_elements_by_path(subitems, elem[1:]);
	#textre = re.compile("\!\[CDATA\[(.*?)\]\]", re.DOTALL);
	def get_text(self,xml):
		textre = re.compile("\!\[CDATA\[(.*?)\]\]", re.DOTALL);
		match = re.search(textre, xml);
		if not match:
			return xml;
		return match.group(1);
	def get_elements(self,xml, elem):
		p = re.compile("<" + elem + ">" + "(.*?)</" + elem + ">", re.DOTALL);
		it = p.finditer(xml);
		result = [];
		for m in it:
			result.append(m.group(1));
		return result;
	def translate(self,w):
		xml = urllib2.urlopen("http://dict.yodao.com/search?keyfrom=dict.python&q="+w+"&xmlDetail=false&doctype=xml").read()
		custom_translations = self.get_elements(xml, "custom-translation");
		#print contents
		means = ''
		for cus in custom_translations:
			contents = self.get_elements_by_path(cus, "translation/content");
			#print contents
			for content in contents[0:5]:
				means = means+self.get_text(content)+'\\n';
		return means